<template>
  <div class="page-container">
    <!-- 顶部按钮 -->
    <div class="btn-container">
      <el-button v-auth-btn="'parking:rule:add_edit'" type="primary" size="medium" @click="onOpenDialog({})">添加停车计费规则</el-button>
      <el-button size="medium" @click="onExportRuleExcel">导出Excel</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="ruleList" class="rule-table" :header-cell-style="{ background: '#f7f8f9' }">
      <el-table-column label="序号" type="index" width="80" />
      <el-table-column label="计费规则编号" prop="ruleNumber" />
      <el-table-column label="计费规则名称" prop="ruleName" />
      <el-table-column label="免费时长（分钟）" prop="freeDuration" />
      <el-table-column label="收费上限（元）">
        <template #default="{ row }">
          {{ row.chargeCeiling ? row.chargeCeiling : '--' }}
        </template>
      </el-table-column>
      <el-table-column label="计费方式">
        <template #default="{ row }">
          {{ chargeTypeObj[row.chargeType] }}
        </template>
      </el-table-column>
      <el-table-column label="计费规则" prop="ruleNameView" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button v-auth-btn="'parking:rule:add_edit'" type="text" size="medium" @click="onOpenDialog(row)">编辑</el-button>
          <el-button v-auth-btn="'parking:rule:remove'" type="text" size="medium" @click="onDeleteRule(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination layout="->, total, prev, pager, next" :total="total" @current-change="onChangePage" />

    <!-- 规则编辑器弹窗 -->
    <RuleEditor ref="ruleEditor" @refresh-rule-list="getRuleList" />
  </div>
</template>

<script>
import { getRuleListAPI, deleteRuleAPI } from '@/api/car/carrule'

import RuleEditor from './RuleEditor'

import { utils, writeFileXLSX } from 'xlsx'

export default {
  name: 'CarRule',
  components: {
    RuleEditor
  },
  data() {
    return {
      ruleList: [],
      total: 0,
      searchParams: {
        page: 1,
        pageSize: 10
      },
      chargeTypeObj: {
        duration: '时长收费',
        turn: '按次收费',
        partition: '分段收费'
      }
    }
  },
  created() {
    // 获取规则列表
    this.getRuleList()
  },
  methods: {
    // 获取规则列表
    async getRuleList() {
      const res = await getRuleListAPI(this.searchParams)
      this.ruleList = res.rows
      this.total = res.total
    },
    // 打开规则编辑器
    onOpenDialog(row) {
      // 打开规则编辑器，当点击添加规则时，参数id为undefined
      this.$refs.ruleEditor.open(row)
    },
    // 导出计费规则excel
    onExportRuleExcel() {
      // 表头英文字段key
      const tableHeaderKeys = ['ruleNumber', 'ruleName', 'freeDuration', 'chargeCeiling', 'chargeType', 'ruleNameView']
      // 表头中文字段value
      const tableHeaderValues = ['计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上线(元)', '计费方式', '计费规则']
      const sheetData = this.ruleList.map(item => {
        const obj = {}
        tableHeaderKeys.forEach(key => {
          obj[key] = item[key]
        })
        return obj
      })
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 创建一个工作表，要求一个对象数组格式
      const worksheet = utils.json_to_sheet(sheetData)
      // 将工作表添加到工作簿中，Data作为工作表名称
      utils.book_append_sheet(workbook, worksheet, 'carRules')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
      // 导出
      writeFileXLSX(workbook, 'SmartPark.xlsx')
    },
    // 删除规则
    async onDeleteRule(id) {
      await deleteRuleAPI(id)
      // 如果删除数据时当前页最后一条数据，且页码大于1，则页码减1
      if (this.ruleList.length === 1 && this.page > 1) {
        this.page--
      }
      // 重新获取规则列表
      this.getRuleList()
      this.$message.success('删除成功')
    },
    // 切换分页器当前页
    onChangePage(val) {
      this.searchParams.page = val
      this.getRuleList()
    },
    // 切换到列表首页
    onChangeFirstPage() {
      this.searchParams.page = 1
      this.getRuleList()
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  .rule-table {
    margin: 20px 0;
  }
}
</style>
